define([
  'text!../../tmpl/tasks/task.html',
  'underscore',
  'backbone'
], function(tmpl, _, Backbone) {
  var TaskView = Backbone.View.extend({
    tagName: 'li',
    className: 'controls well task row',

    template: _.template(tmpl),
    events: {
      'click': 'open',
      'click .check-task': 'toggle'
    },

    initialize: function(options) {
      this.parentView = options.parentView;
    },
    toggle: function(eve) {
      var id = this.model.get('id');
      var $el = this.$el.find('.check-task');
      this.model.set('status', $el[0].checked ? 'completed' : 'needsAction');
      if (this.model.get('status') === 'needsAction') {
        this.model.set('completed', null);
      }

      // this.model.save();
      // return false;
      eve.stopPropagation();
    },

    render: function() {
      var $el = this.$el;
      $el.data('taskId', this.model.get('id'));
      $el.html(this.template(this.model.toJSON()));
      $el.find('.check-task').attr('checked', this.model.get('status').favorited === 'true');

      return this;
    },

    open: function() {
      if (this.parentView.activeTaskView) {
        this.parentView.activeTaskView.close();
      }
      this.$el.addClass('active');
      this.parentView.activeTaskView = this;
      this.parentView.editTask(this.model);
    },

    close: function() {
      this.$el.removeClass('active');
    }
  });

  return TaskView;
})